package com.ruoyi.system.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.MedicalStudentMapper;
import com.ruoyi.system.domain.MedicalStudent;
import com.ruoyi.system.service.IMedicalStudentService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PhysicalStudent;
import com.ruoyi.system.mapper.PhysicalStudentMapper;
import com.ruoyi.system.domain.PositionStudent;
import com.ruoyi.system.mapper.PositionStudentMapper;

/**
 * 警校考生体检面试信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-01
 */
@Service
public class MedicalStudentServiceImpl implements IMedicalStudentService 
{
    @Autowired
    private MedicalStudentMapper medicalStudentMapper;

    @Autowired
    private PhysicalStudentMapper physicalStudentMapper;

    @Autowired
    private PositionStudentMapper positionStudentMapper;

    /**
     * 查询警校考生体检面试信息
     * 
     * @param id 警校考生体检面试信息主键
     * @return 警校考生体检面试信息
     */
    @Override
    public MedicalStudent selectMedicalStudentById(Long id)
    {
        return medicalStudentMapper.selectMedicalStudentById(id);
    }

    /**
     * 查询警校考生体检面试信息列表
     * 
     * @param medicalStudent 警校考生体检面试信息
     * @return 警校考生体检面试信息
     */
    @Override
    public List<MedicalStudent> selectMedicalStudentList(MedicalStudent medicalStudent)
    {
        return medicalStudentMapper.selectMedicalStudentList(medicalStudent);
    }

    /**
     * 新增警校考生体检面试信息
     * 
     * @param medicalStudent 警校考生体检面试信息
     * @return 结果
     */
    @Override
    public int insertMedicalStudent(MedicalStudent medicalStudent)
    {
        // 验证该考生是否已通过体能测评
        PhysicalStudent physical = new PhysicalStudent();
        physical.setRegistrationId(medicalStudent.getRegistrationId());
        physical.setIdCard(medicalStudent.getIdCard());
//        physical.setPhysicalTest("通过");
        List<PhysicalStudent> physicalList = physicalStudentMapper.selectPhysicalStudentList(physical);
        
        if (physicalList == null || physicalList.isEmpty()) {
            throw new ServiceException("该考生未通过体能测评，不能参加体检面试");
        }
        
        return medicalStudentMapper.insertMedicalStudent(medicalStudent);
    }

    /**
     * 修改警校考生体检面试信息
     * 
     * @param medicalStudent 警校考生体检面试信息
     * @return 结果
     */
    @Override
    public int updateMedicalStudent(MedicalStudent medicalStudent)
    {
        // 如果体检面试更新为"通过"，并且该考生已通过资格审查和体能测评，则自动设置最终结果为"通过"
        if ("通过".equals(medicalStudent.getMedicalInterview()) && 
            "通过".equals(medicalStudent.getQualificationReview()) && 
            "通过".equals(medicalStudent.getPhysicalTest())) {
            medicalStudent.setResult("通过");
        }
        
        // 更新考生体检面试信息
        int rows = medicalStudentMapper.updateMedicalStudent(medicalStudent);
        
        // 如果体检面试更新为"通过"，则自动将考生信息添加到职位选择
        if (rows > 0 && "通过".equals(medicalStudent.getMedicalInterview())) {
            // 查询该考生在职位选择中是否已存在
            PositionStudent positionQuery = new PositionStudent();
            positionQuery.setRegistrationId(medicalStudent.getRegistrationId());
            List<PositionStudent> existingPosition = positionStudentMapper.selectPositionStudentList(positionQuery);
            
            // 如果不存在，则添加
            if (existingPosition == null || existingPosition.isEmpty()) {
                PositionStudent newPositionStudent = new PositionStudent();
                // 复制必要信息
                copyStudentBaseInfo(medicalStudent, newPositionStudent);
                // 设置创建者
                if (StringUtils.isNotEmpty(medicalStudent.getUpdateBy())) {
                    newPositionStudent.setCreateBy(medicalStudent.getUpdateBy());
                }
                newPositionStudent.setResult("通过");
                // 插入到职位选择
                positionStudentMapper.insertPositionStudent(newPositionStudent);
            }
        }
        
        return rows;
    }

    /**
     * 批量修改警校考生资格审查结果
     * 
     * @param medicalStudentList 包含学生ID和新资格审查结果的列表
     * @return 结果
     */
    @Override
    public int batchUpdateQualificationReview(List<MedicalStudent> medicalStudentList)
    {
        medicalStudentList.forEach(medicalStudent -> {
            // 更新考生资格审查信息
            medicalStudentMapper.updateMedicalStudent(medicalStudent);

            // 如果体能测评更新为"通过"，则自动将考生信息添加到体检面试
            if ("通过".equals(medicalStudent.getMedicalInterview())) {
                // 查询该考生在体检面试中是否已存在
                PositionStudent physicalQuery = new PositionStudent();
                physicalQuery.setRegistrationId(medicalStudent.getRegistrationId());
                List<PositionStudent> existingPhysical = positionStudentMapper.selectPositionStudentList(physicalQuery);

                // 如果不存在，则添加
                if (existingPhysical == null || existingPhysical.isEmpty()) {
                    PositionStudent newPhysicalStudent = new PositionStudent();
                    // 复制必要信息
                    copyStudentBaseInfo(medicalStudent, newPhysicalStudent);
                    // 设置创建者
                    if (StringUtils.isNotEmpty(medicalStudent.getUpdateBy())) {
                        newPhysicalStudent.setCreateBy(medicalStudent.getUpdateBy());
                    }
                    newPhysicalStudent.setResult("通过");

                    // 插入到体能测评
                    positionStudentMapper.insertPositionStudent(newPhysicalStudent);
                }
            }
        });

        return 1;
    }

    /**
     * 复制考生基本信息
     * 
     * @param source 源对象
     * @param target 目标对象
     */
    private void copyStudentBaseInfo(MedicalStudent source, PositionStudent target) {
        target.setRegistrationId(source.getRegistrationId());
        target.setName(source.getName());
        target.setIdCard(source.getIdCard());
        target.setGender(source.getGender());
        target.setNativeCity(source.getNativeCity());
        target.setWrittenExamNo(source.getWrittenExamNo());
        target.setComputerExamNo(source.getComputerExamNo());
        target.setAdministrativeScore(source.getAdministrativeScore());
        target.setEssayScore(source.getEssayScore());
        target.setProfessionalScore(source.getProfessionalScore());
        target.setTotalScore(source.getTotalScore());
        target.setCompositeScore(source.getCompositeScore());
        target.setInterviewScore(source.getInterviewScore());
        target.setAdministrativeAbsent(source.getAdministrativeAbsent());
        target.setEssayAbsent(source.getEssayAbsent());
        target.setProfessionalAbsent(source.getProfessionalAbsent());
        target.setPoliticalStatus(source.getPoliticalStatus());
        target.setHighestDegree(source.getHighestDegree());
        target.setAcademicDegree(source.getAcademicDegree());
        target.setGraduateSchool(source.getGraduateSchool());
        target.setDepartment(source.getDepartment());
        target.setMajor(source.getMajor());
        target.setPhoneNumber(source.getPhoneNumber());
        target.setQualificationReview(source.getQualificationReview());
        target.setPhysicalTest(source.getPhysicalTest());
        target.setMedicalInterview(source.getMedicalInterview());
    }

    /**
     * 批量删除警校考生体检面试信息
     * 
     * @param ids 需要删除的警校考生体检面试信息主键
     * @return 结果
     */
    @Override
    public int deleteMedicalStudentByIds(Long[] ids)
    {
        return medicalStudentMapper.deleteMedicalStudentByIds(ids);
    }

    /**
     * 删除警校考生体检面试信息信息
     * 
     * @param id 警校考生体检面试信息主键
     * @return 结果
     */
    @Override
    public int deleteMedicalStudentById(Long id)
    {
        return medicalStudentMapper.deleteMedicalStudentById(id);
    }
    
    /**
     * 导入警校考生体检面试信息
     * 
     * @param medicalStudentList 警校考生体检面试信息列表
     * @param updateSupport 是否更新支持，如果已存在，是否更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importMedicalStudent(List<MedicalStudent> medicalStudentList, boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(medicalStudentList) || medicalStudentList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MedicalStudent medicalStudent : medicalStudentList)
        {
            try
            {
                // 验证是否存在这个学生
                MedicalStudent existingStudent = new MedicalStudent();
                if (StringUtils.isNotEmpty(medicalStudent.getIdCard())) {
                    existingStudent.setIdCard(medicalStudent.getIdCard());
                } else if (StringUtils.isNotEmpty(medicalStudent.getRegistrationId())) {
                    existingStudent.setRegistrationId(medicalStudent.getRegistrationId());
                } else {
                    failureNum++;
                    failureMsg.append("<br/>第 " + failureNum + " 条数据导入失败：身份证号和报名序号不能同时为空");
                    continue;
                }
                
                // 验证该考生是否已通过体能测评
                PhysicalStudent physical = new PhysicalStudent();
                if (StringUtils.isNotEmpty(medicalStudent.getIdCard())) {
                    physical.setIdCard(medicalStudent.getIdCard());
                } else {
                    physical.setRegistrationId(medicalStudent.getRegistrationId());
                }
//                physical.setPhysicalTest("通过");
                List<PhysicalStudent> physicalList = physicalStudentMapper.selectPhysicalStudentList(physical);
                
                if (physicalList == null || physicalList.isEmpty()) {
                    failureNum++;
                    failureMsg.append("<br/>第 " + failureNum + " 条数据导入失败：" + medicalStudent.getName() + " 未通过体能测评，不能参加体检面试");
                    continue;
                }
                
                // 如果资格审查、体能测评、体检面试均通过，则自动设置最终结果为"通过"
                if ("通过".equals(medicalStudent.getMedicalInterview()) && 
                    "通过".equals(medicalStudent.getQualificationReview()) && 
                    "通过".equals(medicalStudent.getPhysicalTest())) {
                    medicalStudent.setResult("通过");
                }
                
                List<MedicalStudent> students = selectMedicalStudentList(existingStudent);
                
                if (students != null && students.size() > 0 && updateSupport)
                {
                    medicalStudent.setId(students.get(0).getId());
                    medicalStudent.setUpdateBy(operName);
                    updateMedicalStudent(medicalStudent);
                    successNum++;
                    successMsg.append("<br/>第 " + successNum + " 条数据更新成功");
                    
                    // 如果体检面试为"通过"，则自动流转到职位选择
                    if ("通过".equals(medicalStudent.getMedicalInterview())) {
                        successMsg.append("，并已自动流转到职位选择模块");
                    }
                }
                else if (students != null && students.size() > 0 && !updateSupport)
                {
                    failureNum++;
                    failureMsg.append("<br/>第 " + failureNum + " 条数据已存在：" + medicalStudent.getName());
                }
                else
                {
                    medicalStudent.setCreateBy(operName);
                    insertMedicalStudent(medicalStudent);
                    successNum++;
                    successMsg.append("<br/>第 " + successNum + " 条数据导入成功");
                    
                    // 如果体检面试为"通过"，则自动流转到职位选择
                    if ("通过".equals(medicalStudent.getMedicalInterview())) {
                        successMsg.append("，并已自动流转到职位选择模块");
                    }
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>第 " + failureNum + " 条数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
